// 配置数据库信息
const usersql = require('../../mysql.js')
// 生成随机id
const setId = require('../../assets/id.js')
// 导入构建树形数据的函数
const treeData = require('../../assets/toTreeData.js')

// 根据id查询权限详情信息
exports.getRight = (req, res) => {
    const id = req.query.id
    const sql = 'select * from rights where id=?'
    usersql.query(sql, id, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 0) {
            res.send({ status: 200, message: '获取权限详情成功', data: results[0] })
        } else {
            res.cc('获取失败')
        }
    })
}

// 根据id更改权限详情信息
exports.editRight = (req, res) => {
    const id = req.query.id
    const user = req.body
    const sql = 'update rights set ? where id=?'
    usersql.query(sql, [user,id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 0) {
            res.send({ status: 200, message: '更新权限详情成功', data: user })
        } else {
            res.cc('更新失败')
        }
    })
}

// 添加权限
exports.addRight = (req, res) => {
    const user = req.body
    const sql = 'insert into rights set ?'
    user.id=setId(10000000,99999999)
    usersql.query(sql, user, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 0) {
            res.send({ status: 200, message: '添加权限', data: user })
        } else {
            res.cc('添加失败')
        }
    })
}

// 根据id删除权限
exports.deleteRight = (req, res) => {
    const id = req.query.id
    const sql = 'delete from rights where id=? or pid=?'
    usersql.query(sql, [id,id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 0) {
            res.send({ status: 200, message: '删除权限成功'})
        } else {
            res.cc('删除失败')
        }
    })
}

// 获取所有权限点权限详情信息
exports.getAllRight = (req, res) => {
    const sql = 'select * from rights'
    usersql.query(sql, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 0) {
            const newData = treeData(results, 0, 1)
            res.send({ status: 200, message: '获取所有权限成功', data: newData })
        } else {
            res.cc('获取失败')
        }
    })
}